#include "DatabaseManage.h"

#include <QDebug>
#include <QMessageBox>

DatabaseManage* DatabaseManage::getInstance()
{
    static DatabaseManage instance;
    return &instance;
}

QSqlDatabase DatabaseManage::initDatabase(QString username, QString password, QString databaseName, QString hostName, int port)
{
    QSqlDatabase db = getDatabase(hostName, port, databaseName);
    if (db.isOpen())
    {
        return db;
    }

    // 连接数据库
    db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName(hostName);
    db.setPort(port);
    db.setDatabaseName(databaseName);
    db.setUserName(username);
    db.setPassword(password);

    // 打开连接
    if(db.open())
    {
        qDebug() << "open database success";
        QMessageBox::information(NULL, "标题", "open database success");
    }
    else
    {
        qDebug() << "open database fail";
        QMessageBox::information(NULL, "标题", "open database fail");
    }

    // 添加到缓存
    QString key = QString(keyStr).arg(hostName).arg(port).arg(databaseName);
    dbMap.insert(key, db);

    // 返回数据库对象
    return db;
}

QSqlDatabase DatabaseManage::getDatabase(QString hostName, int port, QString databaseName)
{
    QString key = QString(keyStr).arg(hostName).arg(port).arg(databaseName);
    return dbMap.value(key);
}

void DatabaseManage::initAllDatabaseConnect()
{

}

void DatabaseManage::cleanAllDatabaseConnect()
{
    QList<QSqlDatabase> values = dbMap.values();
    for (int i = 0; i < values.size(); i++) {
        QSqlDatabase db = values.at(i);
        if (db.isOpen())
        {
            db.close();
        }
    }
}

/*************************************** 单例开始 *************************************/
DatabaseManage::DatabaseManage()
{

}

DatabaseManage::DatabaseManage(DatabaseManage& item)
{

}

DatabaseManage&DatabaseManage::operator=(DatabaseManage& item)
{
    return * this;
}

DatabaseManage::~DatabaseManage()
{
    cleanAllDatabaseConnect();
}
/*************************************** 单例结束 *************************************/


